package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : jiang
 * @date : 2023/10/21 16:06
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //创建订单状态
        Orders orders = new Orders();
        //拷贝前端传递的数据
        BeanUtils.copyProperties(ordersSubmitDTO,orders);

        //获取地址簿信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook address = addressBookMapper.getAddressById(addressBookId);
        //判断地址簿是否为空
        if (address == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //判断用户购物车是否为空
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(BaseContext.getCurrentId());
        if (shoppingCarts == null){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //补充数据
        //收货人
        orders.setConsignee(address.getConsignee());
        //手机号
        orders.setPhone(address.getPhone());
        //地址
        orders.setAddress(address.getProvinceName() + address.getCityName() + address.getDistrictName() + address.getDetail());
        //下单用户id
        orders.setUserId(address.getUserId());
        //订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        //添加记录到订单表
        orderMapper.insert(orders);

        //获取订单菜品详情
        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            //创建订单详情对象
            OrderDetail orderDetail = new OrderDetail();
            //拷贝数据
            BeanUtils.copyProperties(cart,orderDetail);
            //订单id赋值
            orderDetail.setOrderId(orders.getId());
            //收集到集合
            list.add(orderDetail);
        }

        //添加记录到订单详情表
        orderDetailMapper.add(list);

        //清空购物车数据
        shoppingCartMapper.deleteShoppingCart(BaseContext.getCurrentId());

        //封装数据返回
        OrderSubmitVO submitVO = new OrderSubmitVO();
        submitVO.setId(orders.getId());
        submitVO.setOrderNumber(orders.getNumber());
        submitVO.setOrderAmount(orders.getAmount());
        submitVO.setOrderTime(orders.getOrderTime());
        return submitVO;
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                //商户订单号
                ordersPaymentDTO.getOrderNumber(),
                //支付金额，单位 元
                new BigDecimal("0.01"),
                //商品描述
                "苍穹外卖订单",
                //微信用户的openid
                user.getOpenid()
        );

        if (jsonObject.getString("code") != null && "ORDERPAID".equals(jsonObject.getString("code"))) {
            throw new OrderBusinessException(MessageConstant.ORDER_PAID_FOR);
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param dto
     */
    @Override
    public void paySuccess(OrdersPaymentDTO dto) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders orders = orderMapper.getByNumberAndUserId(dto.getOrderNumber(), userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders os = Orders.builder()
                .id(orders.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(os);
    }

    /**
     * 查询历史订单
     * @param dto
     * @return
     */
    @Override
    public PageResult pageHistory(OrdersPageQueryDTO dto) {
        //设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //设置用户id
        dto.setUserId(BaseContext.getCurrentId());
        //执行分页查询
        Page<OrderVO> pageList = orderMapper.pageHistory(dto);
        //遍历去到的订单
        pageList.forEach(page->{
            //取出每个订单所包含的商品
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(page.getId());
            //装进orderVO中
            page.setOrderDetailList(orderDetails);
        });

        //封装数据返回
        return new PageResult(pageList.getTotal(),pageList.getResult());
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //执行分页查询
        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);
        //封装数据返回
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrdersDetails(Long id) {
        //查询当前订单
        Orders order = orderMapper.getOrderById(id);
        //查询当前订单的菜品详情
        List<OrderDetail> list = orderDetailMapper.getByOrderId(order.getId());
        //创建orderVO对象
        OrderVO orderVO = new OrderVO();
        //拷贝订单数据
        BeanUtils.copyProperties(order,orderVO);
        //封装菜品数据
        orderVO.setOrderDetailList(list);

        ArrayList<String> arrayList = new ArrayList<>();
        for (OrderDetail od : list) {
            arrayList.add(od.getName());
        }

        orderVO.setOrderDishes(arrayList.toString());

        return orderVO;
    }

    /**
     * 统计各个状态的订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO getOrdersStatistics() {
        //待接单数量
        Integer countToBeConfirmed = orderMapper.getToBeConfirmed();
        //派送中数量
        Integer countDeliveryInProgress = orderMapper.getDeliveryInProgress();
        //待派送数量
        Integer countConfirmed = orderMapper.getConfirmed();

        //封装数据并返回
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(countConfirmed);
        orderStatisticsVO.setDeliveryInProgress(countDeliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(countToBeConfirmed);
        return orderStatisticsVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        //创建order对象 设置状态为已取消 订单状态为已退款
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .build();
        //修改数据库信息
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //根据订单id获取原订单的菜品信息
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        //遍历菜品集合
        orderDetails.forEach(orderDetail -> {
            //创建购物车对象
            ShoppingCart cart = new ShoppingCart();
            //拷贝数据
            BeanUtils.copyProperties(orderDetail,cart);
            //补充数据
            cart.setUserId(BaseContext.getCurrentId());
            cart.setCreateTime(LocalDateTime.now());
            //将订单的菜品添加到购物车
            shoppingCartMapper.addRecord(cart);
        });
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //创建订单对象
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .build();
        //更新数据库中订单状态
        orderMapper.update(orders);
    }

    /**
     * 接单
     * @param orders
     */
    @Override
    public void conFirm(Orders orders) {
        //设置订单状态为已接单
        orders.setStatus(Orders.CONFIRMED);
        //更新数据库信息
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param orders
     */
    @Override
    public void rejection(Orders orders) {
        //修改订单状态
        orders.setStatus(Orders.CANCELLED);
        //修改订单支付状态
        orders.setPayStatus(Orders.REFUND);
        //设置订单拒绝时间
        orders.setCancelTime(LocalDateTime.now());
        //修改数据库订单信息
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //创建订单对象
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }
}
